package com.jfunit.java;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import com.jfunit.java.bean.Data;
import com.jfunit.java.bean.Handler;
import com.jfunit.java.bean.Params;
import com.jfunit.java.bean.View;
import com.jfunit.java.helper.BeanHelper;
import com.jfunit.java.helper.ConfigHelper;
import com.jfunit.java.helper.ControllerHelper;
import com.jfunit.java.mvc.DataContext;
import com.jfunit.java.mvc.HandlerExceptionResolver;
import com.jfunit.java.mvc.HandlerInvoker;
import com.jfunit.java.util.CodeUtil;
import com.jfunit.java.util.JsonUril;
import com.jfunit.java.util.PropsUtil;
import com.jfunit.java.util.ReflectionUtil;
import com.jfunit.java.util.StreamUtil;
import com.jfunit.java.util.StringUtil;
import com.jfunit.java.util.WebUtil;

/**
 * 请求转发器
 * 
 * @author Administrator
 *
 */
@WebServlet(urlPatterns = "/", loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("DispatcherServlet---init-1");
        // 初始化相关Helper类 , 就是加载之前封装好的 Helper等class
        HelperLoader.init();
        // 获取ServletContext对像，用于注册Servlet
        ServletContext servletContext = servletConfig.getServletContext();
        // 注册处理JSP的Servlet,查看了下 返回的是 org.apache.jasper.servlet.JspServlet 说明是框架中的一个servlet
        ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");// 获取注册的 js
                                                                                      // servlet对象
        // System.out.println("ConfigHelper.getAppJspPath():-------"+ConfigHelper.getAppJspPath());
        jspServlet.addMapping(ConfigHelper.getAppJspPath() + "*");
        // 注册处理静态资源的默认servlet
        // 注册servlet。 使用默认的就是放行。 这里就是让客户端请求能获取到资源文件
        // 符合该路径的，会被该servlet执行，而不会转调到我们自己的setvlet
        ServletRegistration defaultServlet = servletContext.getServletRegistration("default");// 处理静态资源
        defaultServlet.addMapping(ConfigHelper.getAppAssetPath() + "*", "/favicon.ico");
    }

    // 获取请求路径
    protected String getRelativePath(HttpServletRequest request) {
        if (request.getAttribute("javax.servlet.include.request_uri") != null) {
            String result = (String) request.getAttribute("javax.servlet.include.path_info");
            if (result == null) {
                result = (String) request.getAttribute("javax.servlet.include.servlet_path");
            } else {
                result = (String) request.getAttribute("javax.servlet.include.servlet_path") + result;
            }
            if ((result == null) || (result.equals(""))) {
                result = "/";
            }
            return result;
        }
        String result = request.getPathInfo();
        if (result == null) {
            result = request.getServletPath();
        } else {
            result = request.getServletPath() + result;
        }
        if ((result == null) || (result.equals(""))) {
            result = "/";
        }
        return result;
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        System.out.println("DispatcherServlet---service-2");
        // 获取请求方法与请求路径
        String requestMethod = request.getMethod().toLowerCase();
        String requestPath = getRelativePath(request);
        /*
         * if (requestPath.equals("/favicon.ico")) { return; }
         */
        // 去掉当前请求路径末尾的“/”
        if (requestPath.endsWith("/")) {
            requestPath = requestPath.substring(0, requestPath.length() - 1);
        }
        // 将“/”请求重定向到首页
        if (requestPath.equals("/")) {
            response.sendRedirect(request.getContextPath() + ConfigHelper.getAppHomePage());
            return;
        }
        // 将“”转发请求到默认首页
        if (StringUtil.isEmpty(requestPath)) {
            request.getRequestDispatcher(ConfigHelper.getAppHomePage()).forward(request, response);
            return;
        }
        System.out.println("----------->1");
        // 初始化 DataContext
        DataContext.init(request, response);
        System.out.println("----------->2");
        // 获取对应的处理类
        Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
        System.out.println("----------->3");
        // 若未找到 Action，则跳转到 404 页面
        if (handler == null) {
            WebUtil.sendError(HttpServletResponse.SC_NOT_FOUND, "", response);
            return;
        }
        System.out.println("----------->4");
        try {
            // 调用 Handler
            HandlerInvoker.invokeHandler(request, response, handler);
        } catch (Exception e) {
            // 处理 Action 异常
            HandlerExceptionResolver.resolveHandlerException(request, response, e);
        } finally {
            // 销毁 DataContext
            DataContext.destroy();
        }

    }

}
